package code.whmmm.util.spring.aspect.util;

import code.whmmm.util.spring.aspect.annotation.CodeAspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * <br/> 创建时间: 2019/12/23 15:48
 *
 * @author Zero
 */
public class AspectUtil {

    public static Method getMethod(JoinPoint joinPoint) {
        MethodSignature methodSignature = getMethodSignature(joinPoint);
        return methodSignature.getMethod();
    }

    private static MethodSignature getMethodSignature(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        return (MethodSignature) signature;
    }

    /**
     * 获取连接点 方法 或 类上的注解。
     *
     * @param joinPoint 连接点
     * @return 注解。
     */
    public static CodeAspect getAnnotation(JoinPoint joinPoint) {
        Method method = getMethod(joinPoint);
        CodeAspect annotation = null;
        if (method != null) {
            annotation = method.getAnnotation(CodeAspect.class);

            if (annotation == null) {
                // 可能注解在类上
                annotation = joinPoint.getTarget().
                        getClass().getAnnotation(CodeAspect.class);

            }
        }
        return annotation;
    }


    public static <T extends Annotation> T getAnnotation(JoinPoint joinPoint, Class<T> clazz) {
        Method method = getMethod(joinPoint);
        T annotation = null;
        if (method != null) {
            annotation = method.getAnnotation(clazz);

            if (annotation == null) {
                // 可能注解在类上
                annotation = joinPoint.getTarget().
                        getClass().getAnnotation(clazz);

            }
        }
        return annotation;
    }

}
